package org.example.handler;

import com.alibaba.fastjson2.JSON;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.entity.ResponseModel;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AuthenticationFailureHandler;

import java.io.IOException;
import java.io.PrintWriter;

public class MyAuthenticationFailureHandler implements AuthenticationFailureHandler {

    @Override
    public void onAuthenticationFailure(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
        // 设置响应头，JSON
        response.setContentType("application/json;charset=utf-8");
        // 创建输出流对象
        PrintWriter writer = response.getWriter();
        //  构建输出数据
        ResponseModel<String> rm = ResponseModel.authFailure("用户名密码不正确");
        // 响应前端数据
        writer.write(JSON.toJSONString(rm));
    }
}
